﻿using IDEAMS.core.deviceClient;
using IDEAMS.core;
using IDEAMS.core.opm;
using IDEAMS.core.queue;
using IDEAMS.model;
using IDEAMS.model.spectrum;
using RealTimeCharts.LineChart;
using RealTimeCharts.LineChart.common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using IDEAMS.model.alarm;

namespace IDEAMS.view.detection
{
    /// <summary>
    /// SpectrumTextDlg.xaml 的交互逻辑
    /// </summary>
    public partial class SpectrumTextDlg : Window
    {
        private readonly object gsLocker = new object(); //光谱图的locker
        /// <summary>
        /// 光谱接收线程
        /// </summary>
        OPM_MsgWorker chartRefreshMsgWorker = null;

        /// <summary>
        /// 光谱刷新线程
        /// </summary>
        private Thread timerThread = null;
        private bool timerThreadStopFlag = false;

        public SpectrumTextDlgViewModel windowViewModel;

        private int channelNo;

        public SpectrumTextDlg()
        {
            InitializeComponent();
            windowViewModel = new SpectrumTextDlgViewModel();
            this.DataContext = windowViewModel;


            this.Loaded += MainWindow_Loaded;
            this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);

            this.btnRefresh.Click += new RoutedEventHandler(Refresh_Click);

            this.btnPass.Click += new RoutedEventHandler(Pass_Click);
            this.btnFail.Click += new RoutedEventHandler(Fail_Click);
            this.btnCancel.Click += new RoutedEventHandler(Cancel_Click);

            this.spectrumCanvas.SizeChanged += new SizeChangedEventHandler(SpectrumCanvas_SizeChanged);

            this.cbChannel.SelectionChanged += new SelectionChangedEventHandler(Channel_SelectionChanged);
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            ReadSpectrum();
        }

        public SpectrumTextDlg(DeviceInfoViewModel deviceInfo) : this()
        {
            windowViewModel.deviceInfo = deviceInfo.Clone();
            switch (deviceInfo.step)
            {
                case ProcessStep.PRE_SPECTRUM_GRATING:
                    windowViewModel.title = "有光栅光谱检测（烤机前）";
                    break;
                case ProcessStep.PRE_SPECTRUM_NO_GRATING:
                    windowViewModel.title = "无光栅光谱检测（烤机前）";
                    break;
                case ProcessStep.POST_SPECTRUM_NO_GRATING:
                    windowViewModel.title = "无光栅光谱检测（烤机后）";
                    break;
                case ProcessStep.POST_SPECTRUM_GRATING:
                    windowViewModel.title = "有光栅光谱检测（烤机后）";
                    break;
                default:
                    break;
            }

            windowViewModel.ReLoad();

            chSeriesColor = MakeLegendColorTable();

            InitChart();

        }

        private void ReadSpectrum()
        {
            DeviceClient client = TW_App.deviceClientManager.Find(windowViewModel.deviceInfo.serialNo);
            if (client == null) return;

            if (client.dataWorker.ssResp == null || client.dataWorker.ssResp.channelNum == 0)
            {
                client.dataWorker.GetSpectrumSummary();
            }

            ChannelItemViewModel channelItemViewModel = windowViewModel.selectedChannelItem;
            try
            {
                new Thread(() => client.dataWorker.ReadSpectrum(channelItemViewModel)).Start();
            }
            catch (Exception)
            {
            }
        }

        private void Channel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedSpectrumDic.Clear();
            if(windowViewModel.selectedChannelItem.no == 0)
            {
                SpectrumPkgBuffer pkgBuffer = new SpectrumPkgBuffer();
                for(int i = 1; i<= channelNo; i++)
                {
                    int channelNo = windowViewModel.selectedChannelItem.no;
                    pkgBuffer.channelNo = i;
                    selectedSpectrumDic.Add(i, pkgBuffer);
                }
            }
            else
            {
                SpectrumPkgBuffer pkgBuffer = new SpectrumPkgBuffer();
                int channelNo = windowViewModel.selectedChannelItem.no;
                pkgBuffer.channelNo = channelNo;
                selectedSpectrumDic.Add(channelNo, pkgBuffer);
            }
            ReadSpectrum();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            timerThreadStopFlag = true;

            StopChartRefreshWorker();
        }


        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            CreateChartSpectrum(false);

            StartChartRefreshWorker();

            timerThread = new Thread(new ThreadStart(() => TimerThreadProc()));
            if (timerThread != null)
            {
                timerThread.Start();
                timerThreadStopFlag = false;
            }

            channelNo = windowViewModel.deviceInfo.deviceParam.nChannel;
            DeviceClient client = TW_App.deviceClientManager.Find(windowViewModel.deviceInfo.serialNo);
            if (client != null)
            {
                if(client.dataWorker.ssResp.channelNum != channelNo)
                {
                    channelNo = client.dataWorker.ssResp.channelNum;

                    // 通道数不一致报警
                    AlarmInfo alarmInfo = new AlarmInfo();
                    alarmInfo.serialNo = windowViewModel.deviceInfo.serialNo;
                    alarmInfo.type = AlarmType.CHANNEL_COUNT_ERROR;
                    alarmInfo.key = windowViewModel.deviceInfo.step + "_" + AlarmType.CHANNEL_COUNT_ERROR;
                    alarmInfo.channelNo = 0;
                    alarmInfo.gratingNo = 0;
                    alarmInfo.step = windowViewModel.deviceInfo.step;
                    alarmInfo.maxDiff = windowViewModel.deviceInfo.deviceParam.nChannel - client.dataWorker.ssResp.channelNum;
                    alarmInfo.startTime = DateTime.Now;
                    alarmInfo.endTime = DateTime.Now;
                    alarmInfo.description = string.Format("设备参数中通道数错误，参数中数量为[{0}]，实际数量为[{1}]个", windowViewModel.deviceInfo.deviceParam.nChannel, client.dataWorker.ssResp.channelNum);
                    TW_App.delegateCollection.SyncAlarm(alarmInfo);
                }
            }

            selectedSpectrumDic.Clear();
            if (windowViewModel.selectedChannelItem.no == 0)
            {
                SpectrumPkgBuffer pkgBuffer = new SpectrumPkgBuffer();
                for (int i = 1; i <= channelNo; i++)
                {
                    int channelNo = windowViewModel.selectedChannelItem.no;
                    pkgBuffer.channelNo = i;
                    selectedSpectrumDic.Add(i, pkgBuffer);
                }
            }
            else
            {
                SpectrumPkgBuffer pkgBuffer = new SpectrumPkgBuffer();
                int channelNo = windowViewModel.selectedChannelItem.no;
                pkgBuffer.channelNo = channelNo;
                selectedSpectrumDic.Add(channelNo, pkgBuffer);
            }
            ReadSpectrum();
        }

        private void TimerThreadProc()
        {
            while (!timerThreadStopFlag)
            {
                int frequence = 2;
                int intervalTm = 1000 / frequence;

                App.Current?.Dispatcher.InvokeAsync((Action)(() =>
                {
                    lock (gsLocker)
                    {
                        //光谱停止时，停止刷新
                        if (selectedSpectrumDic.Count() == 0) return;

                        List<SpectrumPkgBuffer> sortFullSpData = selectedSpectrumDic.Values.OrderBy(x => x.channelNo).ToList();

                        ShowSpectrumData(sortFullSpData);
                    }
                }));

                Thread.Sleep(intervalTm);
            }
        }

        private void ShowSpectrumData(List<SpectrumPkgBuffer> spDataList)
        {
            if (lineChartSpectrum.elemList == null)
            {
                lineChartSpectrum.elemList = new List<List<ValuePoint>>();
            }

            lineChartSpectrum.elemList.Clear();

            ValueRange valueRangeX = new ValueRange();

            //设置数据
            foreach (var data in spDataList)
            {
                List<ValuePoint> valuePoints = new List<ValuePoint>();

                //有可能接收的数据是不按照顺序的，需要排序后保证波长从小到大的顺序
                List<SpectrumAcqData> sortSubData = data.GetData().OrderBy(x => x.subPkgNo).ToList();
                foreach (var subData in sortSubData)
                {
                    for (int i = 0; i < subData.counts; i++)
                    {
                        double valX = subData.startWaveLen + i * (subData.interval / 1000.0);
                        double valY = subData.data[i];

                        valuePoints.Add(new ValuePoint(valX, valY));

                        if (double.IsNaN(valueRangeX.minValue))
                        {
                            valueRangeX.minValue = valX;
                        }
                        else if (valX < valueRangeX.minValue)
                        {
                            valueRangeX.minValue = valX;
                        }

                        if (double.IsNaN(valueRangeX.maxValue))
                        {
                            valueRangeX.maxValue = valX;
                        }
                        else if (valX > valueRangeX.maxValue)
                        {
                            valueRangeX.maxValue = valX;
                        }
                    }
                }

                lineChartSpectrum.elemList.Add(valuePoints);
            }


            lineChartSpectrum.axisScaleWindow.scaleX.valueRange.minValue = valueRangeX.minValue;
            lineChartSpectrum.axisScaleWindow.scaleX.valueRange.maxValue = valueRangeX.maxValue;
            windowViewModel.spectrumDisplayViewModel.waveLenRange.minValue = valueRangeX.minValue;
            windowViewModel.spectrumDisplayViewModel.waveLenRange.maxValue = valueRangeX.maxValue;


            //设置图例
            List<ColorLegendData> colorLegendDataList = new List<ColorLegendData>();

            for (int i = 0; i < spDataList.Count; i++)
            {
                ColorLegendData newData = new ColorLegendData();
                newData.color = chSeriesColor[i];

                newData.text = "通道" + spDataList[i].channelNo;


                colorLegendDataList.Add(newData);
            }

            System.Drawing.Pen borderPen = new System.Drawing.Pen(System.Drawing.Color.Black, 1);
            ColorLegend colorLegend = new ColorLegend(colorLegendDataList, new Font("Arial", 8), borderPen, Position.TopRight);

            lineChartSpectrum.colorLegend = colorLegend;

            lineChartSpectrum.Show(true);
        }

        private void SpectrumCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            CreateChartSpectrum(false);
        }

        private void Pass_Click(object sender, RoutedEventArgs e)
        {
            if (windowViewModel.selectedChannelItem.no != 0)
            {
                MessageBox.Show("请选择全部通道并且正确显示后提交", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            SaveSpectrumData();
            switch (windowViewModel.deviceInfo.step)
            {
                case ProcessStep.PRE_SPECTRUM_GRATING:
                    windowViewModel.deviceInfo.processResult.preSpectrumGrating = true;
                    break;
                case ProcessStep.PRE_SPECTRUM_NO_GRATING:
                    windowViewModel.deviceInfo.processResult.preSpectrumNoGrating = true;
                    break;
                case ProcessStep.POST_SPECTRUM_NO_GRATING:
                    windowViewModel.deviceInfo.processResult.postSpectrumNoGrating = true;
                    break;
                case ProcessStep.POST_SPECTRUM_GRATING:
                    windowViewModel.deviceInfo.processResult.postSpectrumGrating = true;
                    break;
                default:
                    break;
            }

            // 查询当前检测步骤
            int index = TW_App.globalSetting.inspectionSequences.IndexOf((int)windowViewModel.deviceInfo.step);
            if(index == -1)
            {
                MessageBox.Show("当前处于未知检测项，请联系系统管理员","错误",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            if(index == TW_App.globalSetting.inspectionSequences.Count-1)
            {
                windowViewModel.deviceInfo.step = ProcessStep.FINISHED;
            }
            else
            {
                windowViewModel.deviceInfo.step = (ProcessStep)TW_App.globalSetting.inspectionSequences[index + 1];
            }

            //windowViewModel.deviceInfo.step++;
            this.DialogResult = true;
        }

        private void SaveSpectrumData()
        {
            List<List<ValuePoint>> datas = lineChartSpectrum.elemList;
            
            string path = string.Format(TW_App.fileManager.spectrumFile, windowViewModel.deviceInfo.serialNo, windowViewModel.selectedChannelItem.no, (int)windowViewModel.deviceInfo.step);
            string directoryName = Path.GetDirectoryName(path);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            if(windowViewModel.selectedChannelItem.no == 0)
            {
                using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
                {
                    bw.Write(datas.Count); // 通道数量
                    int channelNo = 1;
                    for (int i = 0; i < datas.Count;i++)
                    {
                        bw.Write(channelNo); // 通道号
                        channelNo++;
                        bw.Write(datas[i].Count); // 数据数量
                        foreach (ValuePoint item1 in datas[i])
                        {
                            bw.Write(item1.valX);
                            bw.Write(item1.valY);
                        }
                    }
                }
            }
            else
            {
                using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
                {
                    bw.Write(1); // 通道数量
                    bw.Write(windowViewModel.selectedChannelItem.no); // 通道号
                    bw.Write(datas[0].Count); // 数据数量
                    foreach (ValuePoint item1 in datas[0])
                    {
                        bw.Write(item1.valX);
                        bw.Write(item1.valY);
                    }
                }
            }

        }

        private void Fail_Click(object sender, RoutedEventArgs e)
        {
            switch (windowViewModel.deviceInfo.step)
            {
                case ProcessStep.PRE_SPECTRUM_GRATING:
                    windowViewModel.deviceInfo.processResult.preSpectrumGrating = false;
                    break;
                case ProcessStep.PRE_SPECTRUM_NO_GRATING:
                    windowViewModel.deviceInfo.processResult.preSpectrumNoGrating = false;
                    break;
                case ProcessStep.POST_SPECTRUM_NO_GRATING:
                    windowViewModel.deviceInfo.processResult.postSpectrumNoGrating = false;
                    break;
                case ProcessStep.POST_SPECTRUM_GRATING:
                    windowViewModel.deviceInfo.processResult.postSpectrumGrating = false;
                    break;
                default:
                    break;
            }
            this.DialogResult = true;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }


        #region 光谱相关
        List<System.Drawing.Color> chSeriesColor;
        LineChart lineChartSpectrum = null;

        Dictionary<int, SpectrumPkgBuffer> selectedSpectrumDic = new Dictionary<int, SpectrumPkgBuffer>();
        Dictionary<int, SpectrumPkgBuffer> spectrumRecvBufferDic = new Dictionary<int, SpectrumPkgBuffer>();

        private OPM_MsgWorker CreateChartRefreshWorker()
        {
            OPM_MsgWorker worker = new OPM_MsgWorker();
            worker.handleProc = ChartDataRefreshProc;

            QueueDataType key = QueueDataType.DATA_SP;
            worker.keyList.Add(key);

            return worker;
        }

        private void ChartDataRefreshProc(QueueData msg) // UDP
        {
            lock (gsLocker)
            {
                SpectrumAcqData spData = ((SpectrumZData)msg).spectrumData;
                if (selectedSpectrumDic.ContainsKey(spData.channelNo))
                {
                    if (!spectrumRecvBufferDic.ContainsKey(spData.channelNo))
                    {
                        spectrumRecvBufferDic.Add(spData.channelNo, new SpectrumPkgBuffer());
                    }

                    SpectrumPkgBuffer pkgBuffer = spectrumRecvBufferDic[spData.channelNo];
                    int rn = pkgBuffer.Add(spData);
                    if (rn != 0)
                    {
                        pkgBuffer.Clear();
                        pkgBuffer.Add(spData);//重置后保留新数据
                        return;
                    }
                    else
                    {
                        if (pkgBuffer.isFull())
                        {
                            //从临时区中移除
                            spectrumRecvBufferDic.Remove(spData.channelNo);
                            spectrumRecvBufferDic.Add(spData.channelNo, new SpectrumPkgBuffer());


                            //添加到显示区中
                            if (selectedSpectrumDic.ContainsKey(spData.channelNo))
                            {
                                selectedSpectrumDic.Remove(spData.channelNo);
                            }
                            selectedSpectrumDic.Add(spData.channelNo, pkgBuffer);
                        }
                    }
                }
                else
                {
                    return;
                }


            }
        }

        private void StartChartRefreshWorker()
        {
            if (chartRefreshMsgWorker.IsStop())
            {
                chartRefreshMsgWorker.StartAsync();

                selectedSpectrumDic.Clear();
                List<QueueDataType> keyList = new List<QueueDataType>();
                QueueDataType key = QueueDataType.DATA_SP;
                keyList.Add(key);

                if (windowViewModel.selectedChannelItem != null)
                {
                    int channelNo = windowViewModel.selectedChannelItem.no;

                    SpectrumPkgBuffer pkgBuffer = new SpectrumPkgBuffer();
                    pkgBuffer.channelNo = channelNo;
                    selectedSpectrumDic.Add(channelNo, pkgBuffer);
                }

                chartRefreshMsgWorker.keyList = keyList;
                DeviceClient client = TW_App.deviceClientManager.Find(windowViewModel.deviceInfo.serialNo);
                if (client != null)
                {
                    client.Register(chartRefreshMsgWorker, chartRefreshMsgWorker.keyList);
                }
            }
        }

        private void StopChartRefreshWorker()
        {
            if (!chartRefreshMsgWorker.IsStop())
            {
                chartRefreshMsgWorker.Stop();

                List<QueueDataType> keyList = new List<QueueDataType>();
                QueueDataType key = QueueDataType.DATA_SP;
                keyList.Add(key);

                DeviceClient client = TW_App.deviceClientManager.Find(windowViewModel.deviceInfo.serialNo);
                if (client != null)
                {
                    client.UnRegister(chartRefreshMsgWorker, keyList);
                }
            }
        }

        private void InitChart()
        {
            LoadSpectrumSetting();

            chartRefreshMsgWorker = CreateChartRefreshWorker();
        }

        private int LoadSpectrumSetting()
        {
            int rn = 0;
            try
            {
                SpectrumDisplayViewModel displayViewModel = windowViewModel.spectrumDisplayViewModel;

                displayViewModel.waveLenRange = new ValueRangeViewModel();
                displayViewModel.waveLenRange.minValue = 1510;
                displayViewModel.waveLenRange.maxValue = 1590;

                displayViewModel.dBmRange = new ValueRangeViewModel();
                displayViewModel.dBmRange.minValue = -75;
                displayViewModel.dBmRange.maxValue = 0;

                ObservableCollection<double> refLines = new ObservableCollection<double>();
                displayViewModel.referenceLines = refLines;

            }
            catch (Exception ex)
            {
                return -1;
            }
            return rn;
        }

        private void CreateChartSpectrum(bool reset)
        {
            int width = (int)spectrumCanvas.ActualWidth;
            int height = (int)spectrumCanvas.ActualHeight;

            if (width > 0 && height > 0)
            {
                // 设置image的size
                spectrumImage.Width = width;
                spectrumImage.Height = height;
            }

            SpectrumDisplayViewModel displayViewModel = windowViewModel.spectrumDisplayViewModel;

            if (lineChartSpectrum == null || reset)
            {
                Title chartTitle = new Title(new Padding(10, 10, 10, 5), "光谱图", new Font("Arial", 12, System.Drawing.FontStyle.Bold), new SolidBrush(System.Drawing.Color.Black));

                TitleProperty titlePropertyY = new TitleProperty();
                titlePropertyY.title = "强度(dBm)";
                titlePropertyY.titleTextFont = new Font("Arial", 10, System.Drawing.FontStyle.Bold);
                AxisTitle axisTitle = new AxisTitle(null, titlePropertyY, (int)Position.Left);

                AxisScaleWindow axisScaleWindow = new AxisScaleWindow();
                axisScaleWindow.scaleX.mode = SCALE_SHOW_MODE.Normal;

                axisScaleWindow.scaleX.valueRange.minValue = displayViewModel.waveLenRange.minValue;
                axisScaleWindow.scaleX.valueRange.maxValue = displayViewModel.waveLenRange.maxValue;


                ScaleLineProperty linePropertyX = new ScaleLineProperty();
                linePropertyX.color = System.Drawing.Color.LightGray;
                linePropertyX.width = 1;
                linePropertyX.type = LineType.LongDashed;
                axisScaleWindow.scaleX.lineProperty = linePropertyX;
                axisScaleWindow.scaleX.scaleTextFormat = "0:F3";

                axisScaleWindow.scaleY.mode = SCALE_SHOW_MODE.Normal;
                axisScaleWindow.scaleY.valueRange.minValue = displayViewModel.dBmRange.minValue;
                axisScaleWindow.scaleY.valueRange.maxValue = displayViewModel.dBmRange.maxValue;
                ScaleLineProperty linePropertyY = new ScaleLineProperty();
                linePropertyY.color = System.Drawing.Color.LightGray;
                linePropertyY.width = 1;
                linePropertyY.type = LineType.LongDashed;
                axisScaleWindow.scaleY.lineProperty = linePropertyY;

                axisScaleWindow.UpdateScaleValue();

                //参考线
                List<ReferenceLine> referenceLines = new List<ReferenceLine>();
                ObservableCollection<double> lineDataList = displayViewModel.referenceLines;
                foreach (var data in lineDataList)
                {
                    ReferenceLine line = new ReferenceLine(data);
                    referenceLines.Add(line);
                }
                axisScaleWindow.referenceLines = referenceLines;

                List<int> channelNoList = new List<int>();
                channelNoList.Add(1);

                Pen borderPen = new Pen(Color.Black, 1);
                ColorLegend colorLegend = MakeLegend(channelNoList, new Font("Arial", 8), borderPen);

                lineChartSpectrum = new LineChart(width, height, System.Drawing.Color.AliceBlue, chartTitle, axisTitle, axisScaleWindow, colorLegend);
                lineChartSpectrum.isColorLengendShow = false;
            }
            else
            {
                lineChartSpectrum.ReSize(width, height);
            }

            spectrumImage.Source = lineChartSpectrum.GetSource();

            lineChartSpectrum.Clear();
            lineChartSpectrum.Show(true);
        }

        private void ShowDataSpectrum(List<SpectrumPkgBuffer> spDataList)
        {
            if (lineChartSpectrum.elemList == null)
            {
                lineChartSpectrum.elemList = new List<List<ValuePoint>>();
            }

            lineChartSpectrum.elemList.Clear();

            ValueRange valueRangeX = new ValueRange();

            // 设置数据
            foreach (var data in spDataList)
            {
                List<ValuePoint> valuePoints = new List<ValuePoint>();

                //有可能接收的数据是不按照顺序的，需要排序后保证波长从小到大的顺序
                List<SpectrumAcqData> sortSubData = data.GetData().OrderBy(x => x.subPkgNo).ToList();
                foreach (var subData in sortSubData)
                {
                    for (int i = 0; i < subData.counts; i++)
                    {
                        double valX = subData.startWaveLen + i * (subData.interval / 1000.0);
                        double valY = subData.data[i];

                        valuePoints.Add(new ValuePoint(valX, valY));

                        if (double.IsNaN(valueRangeX.minValue))
                        {
                            valueRangeX.minValue = valX;
                        }
                        else if (valX < valueRangeX.minValue)
                        {
                            valueRangeX.minValue = valX;
                        }

                        if (double.IsNaN(valueRangeX.maxValue))
                        {
                            valueRangeX.maxValue = valX;
                        }
                        else if (valX > valueRangeX.maxValue)
                        {
                            valueRangeX.maxValue = valX;
                        }
                    }
                }

                lineChartSpectrum.elemList.Add(valuePoints);
            }


            lineChartSpectrum.axisScaleWindow.scaleX.valueRange.minValue = valueRangeX.minValue;
            lineChartSpectrum.axisScaleWindow.scaleX.valueRange.maxValue = valueRangeX.maxValue;
            windowViewModel.spectrumDisplayViewModel.waveLenRange.minValue = valueRangeX.minValue;
            windowViewModel.spectrumDisplayViewModel.waveLenRange.maxValue = valueRangeX.maxValue;


            //设置图例
            List<ColorLegendData> colorLegendDataList = new List<ColorLegendData>();

            for (int i = 0; i < spDataList.Count; i++)
            {
                ColorLegendData newData = new ColorLegendData();
                newData.color = chSeriesColor[i];
                newData.text = "通道" + spDataList[i].channelNo;

                colorLegendDataList.Add(newData);
            }

            System.Drawing.Pen borderPen = new System.Drawing.Pen(System.Drawing.Color.Black, 1);
            ColorLegend colorLegend = new ColorLegend(colorLegendDataList, new Font("Arial", 8), borderPen, Position.TopRight);

            lineChartSpectrum.colorLegend = colorLegend;

            lineChartSpectrum.Show(true);
        }

        private ColorLegend MakeLegend(List<int> channelNoList, Font font, System.Drawing.Pen borderPen)
        {
            List<ColorLegendData> colorLegendDataList = new List<ColorLegendData>();

            foreach (var v in channelNoList)
            {
                ColorLegendData newData = new ColorLegendData();
                newData.color = chSeriesColor[v - 1];
                newData.text = "通道" + v.ToString();

                colorLegendDataList.Add(newData);
            }

            ColorLegend colorLegend = new ColorLegend(colorLegendDataList, font, borderPen, Position.TopRight);
            return colorLegend;

        }
        private List<System.Drawing.Color> MakeLegendColorTable()
        {
            List<System.Drawing.Color> colorList = new List<System.Drawing.Color>();
            int r = 0, g = 0, b = 0;
            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0xFF, 0x00));

            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0x00, 0x00));

            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0x00, 0x00));

            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0x00, 0xFF));

            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0xFF, 0x00));
            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0x00, 0xFF));
            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0xFF, 0xFF));

            colorList.Add(System.Drawing.Color.FromArgb(0x80, 0x00, 0x00));
            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0x80, 0x00));
            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0x00, 0x80));

            colorList.Add(System.Drawing.Color.FromArgb(0x80, 0x80, 0x00));
            colorList.Add(System.Drawing.Color.FromArgb(0x80, 0x00, 0x80));
            colorList.Add(System.Drawing.Color.FromArgb(0x00, 0x80, 0x80));

            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0xB0, 0xB0));
            colorList.Add(System.Drawing.Color.FromArgb(0x80, 0x80, 0x80));
            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0x40, 0x40));

            colorList.Add(System.Drawing.Color.FromArgb(0xA0, 0x80, 0x20));
            colorList.Add(System.Drawing.Color.FromArgb(0x20, 0x80, 0x20));


            colorList.Add(System.Drawing.Color.FromArgb(0x32, 0xCD, 0x32));
            colorList.Add(System.Drawing.Color.FromArgb(0x48, 0xD1, 0xCC));
            colorList.Add(System.Drawing.Color.FromArgb(0x64, 0x95, 0xED));
            colorList.Add(System.Drawing.Color.FromArgb(0x41, 0x69, 0xE1));
            colorList.Add(System.Drawing.Color.FromArgb(0xEE, 0x82, 0xEE));
            colorList.Add(System.Drawing.Color.FromArgb(0x8A, 0x2B, 0xE2));
            colorList.Add(System.Drawing.Color.FromArgb(0xDB, 0x70, 0x93));
            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0xE4, 0xE1));
            colorList.Add(System.Drawing.Color.FromArgb(0x70, 0x80, 0x90));
            colorList.Add(System.Drawing.Color.FromArgb(0xD2, 0x69, 0x1E));
            colorList.Add(System.Drawing.Color.FromArgb(0xF0, 0x80, 0x80));
            colorList.Add(System.Drawing.Color.FromArgb(0xDC, 0x14, 0x3C));
            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0xD7, 0x00));
            colorList.Add(System.Drawing.Color.FromArgb(0xFF, 0xFA, 0xCD));

            return colorList;
        }
        #endregion
    }

    public class SpectrumTextDlgViewModel : ViewModelBase
    {
        public SpectrumTextDlgViewModel()
        {
            channelItems = new ObservableCollection<ChannelItemViewModel>();
            ChannelItemViewModel ci = new ChannelItemViewModel();
            ci.no = 0;
            ci.name = "全部";
            channelItems.Add(ci);
            for (int i = 1; i<= 32; i++)
            {
                ci = new ChannelItemViewModel();
                ci.no = i;
                ci.name = "通道" + i;
                channelItems.Add(ci);
            }
            selectedChannelItem = channelItems[0];

            spectrumDisplayViewModel = new SpectrumDisplayViewModel();
        }

        public void ReLoad()
        {
            channelItems.Clear();
            ChannelItemViewModel ci = new ChannelItemViewModel();
            ci.no = 0;
            ci.name = "全部";
            channelItems.Add(ci);
            for (int i = 1; i <= deviceInfo.deviceParam.nChannel; i++)
            {
                ci = new ChannelItemViewModel();
                ci.no = i;
                ci.name = "通道" + i;
                channelItems.Add(ci);
            }
            selectedChannelItem = channelItems[0];
        }

        private string m_title;
        public string title
        {
            get { return m_title; }
            set
            {
                m_title = value;
                NotifyPropertyChanged();
            }
        }

        private DeviceInfoViewModel m_deviceInfo;
        public DeviceInfoViewModel deviceInfo
        {
            get { return m_deviceInfo; }
            set
            {
                m_deviceInfo = value;
                NotifyPropertyChanged();
            }
        }

        private ObservableCollection<ChannelItemViewModel> m_channelItems;
        public ObservableCollection<ChannelItemViewModel> channelItems
        {
            get { return m_channelItems; }
            set
            {
                m_channelItems = value;
                NotifyPropertyChanged();
            }
        }

        private ChannelItemViewModel m_selectedChannelItem;
        public ChannelItemViewModel selectedChannelItem
        {
            get { return m_selectedChannelItem; }
            set
            {
                m_selectedChannelItem = value;
                NotifyPropertyChanged();
            }
        }

        private SpectrumDisplayViewModel m_spectrumDisplayViewModel;
        public SpectrumDisplayViewModel spectrumDisplayViewModel
        {
            get { return m_spectrumDisplayViewModel; }
            set
            {
                m_spectrumDisplayViewModel = value;
                NotifyPropertyChanged();
            }
        }
    }
}
